using System.IO;
using Ionic.Zip;
using Ionic.Zlib;

namespace ImpEx.Engine
{
    public class ZipPacker : ZipFile
    {
        public static string PrevFile;

        public ZipPacker()
        {
        }

        public ZipPacker(string fileName) : base(fileName)
        {
        }

        public static void PackProgress(object sender, SaveProgressEventArgs e)
        {
            if (e.CurrentEntry != null && PrevFile != e.CurrentEntry.FileName)
            {
                Logger.WriteLine("pack: {0}", e.CurrentEntry.FileName);
                PrevFile = e.CurrentEntry.FileName;
            }
        }

        public void SavePackage(string fileName)
        {
            PrevFile = string.Empty;
            SaveProgress += PackProgress;
            CompressionLevel = CompressionLevel.LEVEL9_BEST_COMPRESSION;
            Save(fileName);
        }

        public void UnpackDirectory(string packPath, string tmpDirectory)
        {
            packPath.ToLowerInvariant();
            foreach (string s1 in EntryFileNames)
            {
                string name = (s1.StartsWith("/")) ? s1 : s1 + "/";

                if (name.StartsWith(packPath))
                {
                    Extract(s1, tmpDirectory);
                }
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="sourcePath"></param>
        /// <param name="packPath"></param>
        public string PackFile(string sourcePath, string packPath)
        {
            sourcePath = FileTools.FormatFileName(sourcePath);
            packPath = FileTools.FormatFolderName(packPath);

            string filePath =
                FileTools.PackPathFormat(packPath + Path.GetFileName(sourcePath));
            if (this[filePath] == null)
            {
                string packpath = FileTools.PackPathFormat(packPath);
                AddFile(sourcePath, packpath);
            }
            return filePath;
        }

        public string PackDirectory(string sourcePath, string packPath)
        {
            packPath = FileTools.FormatFolderName(
                FileTools.FormatFolderName(packPath) + Path.GetFileName(sourcePath));
            sourcePath = FileTools.FormatFolderName(sourcePath);

            foreach (string file in Directory.GetFiles(sourcePath, "*", SearchOption.AllDirectories))
            {
                string outputFolder =
                    FileTools.FormatFolderName(packPath) +
                    FileTools.FormatRelativePath(
                        sourcePath, FileTools.FormatFolderName(Path.GetDirectoryName(file)));

                PackFile(file, FileTools.FormatFolderName(outputFolder));
            }
            return FileTools.PackPathFormat(packPath);
        }
    }
}